
import cv2
import numpy as np
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QImage

def QImage2Mat(incomingImage):
    width = incomingImage.width()
    height = incomingImage.height()
    ptr = incomingImage.bits()
    ptr.setsize(incomingImage.byteCount())
    arr = np.array(ptr).reshape(height, width, 4)  # Copies the data
    # OpenCV通常使用BGR格式，如果需要，可以转换颜色空间
    arr = cv2.cvtColor(arr, cv2.COLOR_RGBA2RGB)
    return arr

def cvimg_to_qtimg(img):
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    x = img.shape[1]
    y = img.shape[0]
    frame = QImage(img.data, x, y, x * 3, QImage.Format_RGB888)
    return frame


 # 获取屏幕截图
def get_screenshot(hwnd):
    screen = QApplication.primaryScreen()
    img = screen.grabWindow(hwnd).toImage()
    image = QImage2Mat(img)

    dpi = 1
    h_img, w_img = image.shape[:2]
    image = image[0:int(h_img/dpi), 0:int(w_img/dpi)]

    return image, hwnd


def adjust_hsv(hsv, sat_scale=6, val_scale=2):
    # 分离HSV通道
    h, s, v = cv2.split(hsv)

    # 增加饱和度和亮度
    s = cv2.convertScaleAbs(s, alpha=sat_scale, beta=0)
    v = cv2.convertScaleAbs(v, alpha=val_scale, beta=0)

    # 合并HSV通道
    hsv_scaled = cv2.merge((h, s, v))
    return hsv_scaled

def similarity_to_grayscale(image, target_color):


    # 确保target_color是RGB格式（如果它不是的话）
    target_rgb = tuple(reversed(target_color)) if len(target_color) == 3 and max(target_color) > 1 else target_color

    # 初始化一个与原图大小相同的数组用于存储相似度值
    similarity_map = np.zeros_like(image[:, :, 0])  # 只取一个通道，因为我们生成的是灰度图

    # 遍历图像的每个像素
    for i in range(image.shape[0]):
        for j in range(image.shape[1]):

            b = image[i, j][0] - target_color[0]
            g = image[i, j][1] - target_color[1]
            r = image[i, j][2] - target_color[2]

            sum = abs(b) + abs(g) + abs(r)
            # 一个更通用的方法是使用归一化和缩放
            similarity = 255 * (1 - sum / (3*255))
            # 其中max_possible_distance是可能的最大距离（在这个例子中是sqrt(3*255^2)）

            similarity_map[i, j] = similarity

            # 返回灰度图
    return similarity_map.astype(np.uint8)
